package org.zakariya.stickyheadersapp.slice;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.components.element.VectorElement;
import org.zakariya.stickyheaders.ActionType;
import org.zakariya.stickyheaders.StickyHeaderLayoutManager;
import org.zakariya.stickyheaders.Utils;
import org.zakariya.stickyheaders.callback.ClickCallback;
import org.zakariya.stickyheaders.model.HeaderModel;
import org.zakariya.stickyheaders.model.ItemModel;
import org.zakariya.stickyheadersapp.ResourceTable;
import org.zakariya.stickyheadersapp.adapter.CollapseHeaderAdapter;
import org.zakariya.stickyheadersapp.tool.TopToolUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
 * CollapsingHeadersSlice
 *
 * @since 2021-08-20
 */
public class CollapsingHeadersSlice extends AbilitySlice {
    private CollapseHeaderAdapter adapter;
    private List<ItemModel> dataList;
    private int numSections;
    private int numItemsPerSection;
    private ListContainer listContainer;
    private HashMap<String, ArrayList<ItemModel>> map = new HashMap<>();
    private StickyHeaderLayoutManager headerDecor;
    private Image iv_bottom;
    private Image iv_remove;
    private Image iv_menu;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_collapsing_headers);
        initComponent();
    }

    private void initComponent() {
        iv_bottom = (Image) findComponentById(ResourceTable.Id_iv_bottom);
        iv_remove = (Image) findComponentById(ResourceTable.Id_iv_remove);
        iv_menu = (Image) findComponentById(ResourceTable.Id_iv_menu);
        iv_bottom.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                TopToolUtils.showScrollTool(getContext(), listContainer);
            }
        });

        iv_remove.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                TopToolUtils.showViewTool(getContext(), listContainer, dataList);
            }
        });

        iv_menu.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                TopToolUtils.showReloadTool(getContext(), listContainer);
            }
        });
        Image image = (Image) findComponentById(ResourceTable.Id_icon_back);
        image.setClickedListener(component -> terminateAbility());
        Text headerText = (Text) findComponentById(ResourceTable.Id_sticky_text);
        Text indexText = (Text) findComponentById(ResourceTable.Id_index_text);
        Button collapse = (Button) findComponentById(ResourceTable.Id_collapseBtn);
        DependentLayout layout = (DependentLayout) findComponentById(ResourceTable.Id_layout_overlap);
        listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_collapsing_headers);
        numSections = 3;
        numItemsPerSection = 10;
        dataList = Utils.getStickyList(numSections, numItemsPerSection, false, HeaderModel.TYPE_70vp);
        adapter = new CollapseHeaderAdapter(this, dataList, mClickCallback);
        listContainer.setItemProvider(adapter);
        headerDecor = new StickyHeaderLayoutManager(listContainer, layout, headerText, indexText, collapse, mClickCallback);
        headerDecor.setDataList(dataList,true);
    }

    private final ClickCallback mClickCallback = new ClickCallback() {
        @Override
        public void onClick(int index, ActionType type, String clickSource, Button collapse) {
            int clickHeadPos = 0;
            //找到点击的header位置
            for (int i = 0; i < dataList.size(); i++) {
                if (dataList.get(i).isHeader()) {
                    if (dataList.get(i).getTitle().equals(dataList.get(index).getTitle())) {
                        clickHeadPos = i;
                    }
                }
            }
            setSectionIsCollapsed(clickHeadPos, collapse);
        }
    };

    /**
     * Mark that a section is collapsed or not. By default sections are not collapsed and draw
     * all their child items. By "collapsing" a section, the child items are hidden.
     *
     * @param clickHeadPos clickHeadPos
     * @param collapse collapse
     */
    private void setSectionIsCollapsed(int clickHeadPos, Button collapse) {
        ItemModel model = null;
        model = dataList.get(clickHeadPos);
        if (map.containsKey(model.getTitle())) {
            ((HeaderModel) dataList.get(clickHeadPos)).setToggle(false);
            ArrayList<ItemModel> data = map.get(model.getTitle());
            dataList.addAll(clickHeadPos + 1, data);
            map.remove(model.getTitle());
            if (collapse != null) {
                collapse.setBackground(new VectorElement(this, ResourceTable.Graphic_ic_expand_less_black_24dp));
            }
        } else {
            ((HeaderModel) dataList.get(clickHeadPos)).setToggle(true);
            ArrayList<ItemModel> itemModels = new ArrayList<>();
            for (int i2 = clickHeadPos; i2 < dataList.size(); i2++) {
                ItemModel itemModel = dataList.get(i2);
                if (!itemModel.isHeader() && itemModel.getTitle().split("/")[0].equals(model.getTitle())) {
                    itemModels.add(itemModel);
                }
                if (itemModel.isFooter()) {
                    itemModels.add(itemModel);
                    break;
                }
            }
            if (map.containsKey(model.getTitle())) {
                itemModels.clear();
                return;
            }
            map.put(model.getTitle(), itemModels);
            dataList.removeAll(itemModels);
            if (collapse != null) {
                collapse.setBackground(new VectorElement(this, ResourceTable.Graphic_ic_expand_more_black_24dp));
            }
        }
        buildSectionIndex();
    }

    private void buildSectionIndex() {
        int toggleNum = 0;
        HeaderModel headerModel = null;
        for (int i = 0; i < dataList.size(); i++) {
            if (i != 0) {
                if (dataList.get(i).isHeader()) {
                    if (!dataList.get(i - 1).isHeader()) {
                        toggleNum += 1;
                    }
                    HeaderModel model = (HeaderModel) dataList.get(i);
                    int ratio = numItemsPerSection * toggleNum;
                    int index = Integer.parseInt(model.getTitle()) * 2;
                    headerModel = new HeaderModel(model.getTitle(), model.getMessage(), model.getType(), ratio + index,ratio+index);
                    headerModel.setToggle(model.isToggle());
                    dataList.remove(i);
                    dataList.add(i, headerModel);
                }
            }
        }
        headerDecor.setDataList(dataList,true);
        adapter.notifyDataChanged();
    }
}
